﻿using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Blazor.Core;

public class IPAddressConverter: JsonConverter<IPAddress>
{
    public override void WriteJson(JsonWriter writer, IPAddress? value, JsonSerializer serializer)
    {
        JToken.FromObject(value?.ToString() ?? string.Empty).WriteTo(writer);
    }

    public override IPAddress? ReadJson(JsonReader reader, Type objectType, IPAddress? existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        var s = JToken.Load(reader).ToString();
        if (string.IsNullOrWhiteSpace(s))
        {
            return null;
        }
        
        return !IPAddress.TryParse(s, out var result) ? null : result;
    }
}